package com.fw.application.controller;


import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.UserController;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.WechatForm;
import com.fw.system.web.model.form.WechatInfoForm;
import com.fw.system.web.model.vo.CountUserAndNowMapPointVo;
import com.fw.system.web.model.vo.FootCityVo;
import com.fw.system.web.model.vo.UserCodeVo;
import com.fw.system.web.service.*;
import com.fw.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.time.Duration;
import java.time.LocalDateTime;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 客户端用户表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/web/user")
@CrossOrigin
@Api(tags = "用户相关")
@Slf4j
public class TbUserController implements UserController {


    @Autowired
    private ITbUserService userService;
    @Autowired
    private ITbCityCodeService cityCodeService;
    @Autowired
    private ITbSysRuleService ruleService;
    @Autowired
    private ITbFriendsService friendsService;
    @Autowired
    private IdXD idXD;
    @Autowired
    private ITbIntegralLogService logService;
    @Autowired
    private ITbConutrySortService conutrySortService;
    @Autowired
    private ITbAddressService addressService;


    /**
     * 预登陆接口
     */
    @GetMapping("/readrLogin/{code}")
    @ApiOperation(value = "根据code 返回 小程序端所需内容", notes = "此接口不进行注册操作!但是返回token 操作,进行无感")
    public Result<UserCodeVo> readrLogin(@PathVariable String code) {
        return userService.loginByCode(code);
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @PostMapping("/logon")
    @ApiModelProperty(value = "根据 login 接口返回的信息,二次拉取用户详细信息", notes = "登录接口,返回token")
    public Result<String> logon(@RequestBody WechatForm wechatForm) {
        // 解密用户信息
        return success(userService.login(wechatForm));
    }

    /**
     * 获取用户运动相关
     */
    @PostMapping("/runData")
    @ApiModelProperty("/获取用户运动")
    public synchronized Result<FootCityVo> runData(@RequestBody WechatInfoForm wechatInfoForm) throws InterruptedException {
        TbUser user = getUser();
        TbSysRule startAndEndTime = ruleService.getById(8);
        if (LocalDateTime.now().compareTo(startAndEndTime.getStartTime()) < 0)
            return new Result<FootCityVo>().fail(500, "活动未开始");
        if (LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) > 0) {
            return new Result<FootCityVo>().fail(500, "活动已结束");
        }
        return success(userService.runData(user, wechatInfoForm));
    }


    @GetMapping("/indexCountUserAndNowMapPoint")
    @ApiOperation("首页统计,战队、当前位置、参与活动人数")
    public Result indexCountUserAndNowMapPoint() {

        TbUser user = this.getUser();
        CountUserAndNowMapPointVo nowMapPointVo = Builder.of(CountUserAndNowMapPointVo::new).build();
        nowMapPointVo.setNickName(cityCodeService.getById(user.getCityCode()).getNickName());
        nowMapPointVo.setNowCity(cityCodeService.getOne(Wrappers.<TbCityCode>lambdaQuery()
                .eq(TbCityCode::getSortCode, user.getNowCityCount())).getCityName());
        nowMapPointVo.setCountUser(Integer.parseInt(ruleService.getById("16").getRuleValue()) +
                userService.count());
        return success(nowMapPointVo);
    }

    @GetMapping("/openSelectUserNum")
    @ApiOperation("不用登陆单独返回系统用户数量")
    public Result openSelectUserNum() {
        return success(Integer.parseInt(ruleService.getById("16").getRuleValue()) +
                userService.count());
    }

    @GetMapping("/getUserInfo")
    @ApiOperation("获取当前登陆用户信息getUserInfo")
    public Result getUserInfo() {
        if (this.getUser().getIsState().equals(0))
            return new Result().fail(50500, "当前用户被封禁");
        return success(this.getUser());
    }


    @GetMapping("/shareBindingFriends/{code}")
    @ApiOperation("分享绑定好友关系")
    private Result shareBindingFriends(@PathVariable String code) {

        if (!this.getUser().getInviteCode().equals(code)) {
            TbSysRule rule = ruleService.getById(13);
            TbUser one = userService.getOne(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getInviteCode, code));

            Assert.isTrue(one != null, "用户不存在");
            TbFriends friends = friendsService.getOne(Wrappers.<TbFriends>lambdaQuery().eq(TbFriends::getUserId, this.getUser().getId()).eq(TbFriends::getFriendsId, one.getId()));
            Assert.isTrue(friends == null, "已经绑定好友");
            Builder.of(TbFriends::new).with(TbFriends::setId, idXD.nextId())
                    .with(TbFriends::setCreateTime, LocalDateTime.now())
                    .with(TbFriends::setUserId, this.getUser().getId())
                    .with(TbFriends::setFriendsId, one.getId()).build().insert();
            //为分享者添加好友信息
            Builder.of(TbFriends::new).with(TbFriends::setId, idXD.nextId())
                    .with(TbFriends::setCreateTime, LocalDateTime.now())
                    .with(TbFriends::setUserId, one.getId())
                    .with(TbFriends::setFriendsId, this.getUser().getId()).build().insert();
            TbSysRule startAndEndTime = ruleService.getById(8);
            if (LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) <= 0) {
                //为分享者增加积分
                logService.addIntegral(Builder
                        .of(TbIntegralLog::new).with(TbIntegralLog::setIntegralName, rule.getRuleKey())
                        .with(TbIntegralLog::setUserId, one.getId())
                        .with(TbIntegralLog::setIntegralNum, Integer.parseInt(rule.getRuleValue()))
                        .with(TbIntegralLog::setIsType, 1).build());
            }
        }

        return success();
    }

    @GetMapping("/getQr")
    @ApiOperation("邀请二维码")
    public Result getQr(@RequestParam String userId, OutputStream outputStream) {
        if (StringUtils.isNotBlank(userId) && !userId.equals("undefined")) {
            String uri = "https://tubu-api.zhizhanyun.cn?id=" + userService.getById(userId).getInviteCode();
            try {
                QrCodeUtil.generate(uri, 200, 200, "png", outputStream);
                return success();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return success();
    }




    @Autowired
    private ITbUserCityJoinService joinService;
    @Autowired
    private ITbWechatFootService wechatFootService;

    @GetMapping("/test")
    public void test() {
        log.info("统计全国排行定时任务启动了....");
        TbSysRule startAndEndTime = ruleService.getById(8);
        if (LocalDateTime.now().compareTo(startAndEndTime.getStartTime()) < 0)
            return;
        if (LocalDateTime.now().compareTo(startAndEndTime.getEndTime()) > 0) {
            return;
        }
        userService.list(Wrappers.<TbUser>lambdaQuery().ge(TbUser::getNowCityCount, 1).eq(TbUser::getIsState, 1)).parallelStream().forEach(map -> {
            TbConutrySort one = conutrySortService.getOne(Wrappers.<TbConutrySort>lambdaQuery().eq(TbConutrySort::getUserId, map.getId()));
            if (one == null) {
                one = new TbConutrySort();
                one.setId(idXD.nextId());
            }

            one.setCityName(cityCodeService.getById(joinService.getOne(Wrappers.<TbUserCityJoin>lambdaQuery().eq(TbUserCityJoin::getUserId, map.getId()).eq(TbUserCityJoin::getIsType, 1)).getCityCode()).getCityName());
            one.setCountFool(map.getCountFool());
            one.setNickName(map.getNickName());
            one.setImgUrl(map.getImgUrl());
            one.setUserId(map.getId());
            one.setNowCountCity(map.getNowCityCount());
            TbWechatFoot tbWechatFoot = wechatFootService.list(Wrappers.<TbWechatFoot>lambdaQuery().eq(TbWechatFoot::getUserId, map.getId()).orderByAsc(TbWechatFoot::getCreateTime)).get(0);
            TbUserCityJoin tbUserCityJoin = joinService.list(Wrappers.<TbUserCityJoin>lambdaQuery().eq(TbUserCityJoin::getUserId, map.getId()).orderByDesc(TbUserCityJoin::getCreateTime)).get(0);
            //计算时差毫秒
            one.setCountTime(Duration.between(tbWechatFoot.getCreateTime(), tbUserCityJoin.getCreateTime()).toMillis());
            one.setCountDayTime(DateUtil.formatBetween(one.getCountTime(), BetweenFormatter.Level.MILLISECOND));
            conutrySortService.saveOrUpdate(one);
        });

    }


}

